package com.xxgc.demo.controller;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.xxgc.demo.controller.result.Result;
import com.xxgc.demo.entity.Users;
import com.xxgc.demo.service.IUsersService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.net.SocketTimeoutException;
import java.util.Set;

/**
 * @Author: Sjy
 * @Date :2023/10/13 - 10 - 13 - 10:57
 * 多数据源配置
 */
@Slf4j
@Tag(name = "数据源")
@RestController
@RequestMapping("/data_source")
public class MoreDataSourceController {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private IUsersService usersService;

    @Operation(summary = "查询所有数据源",description = "查询数据源")
    @GetMapping("/getAllDataSource")
    public Result<Set<String>> getAllDataSource(){
        //把数据源转druid数据源
        DynamicRoutingDataSource drDataSource = (DynamicRoutingDataSource) dataSource;
        //便利所有数据源
        Set<String> set = drDataSource.getDataSources().keySet();
        return Result.ok(set);
    }

    @Operation(summary = "添加用户",description = "用户")
    @PostMapping("/addUsers")
    public Result addUsers(@RequestBody Users users){
        usersService.save(users);
        return Result.ok();
    }

    @Operation(summary = "数据库出问题",description = "链接超时")
    @PostMapping("/error")
    public Result error() throws SocketTimeoutException {
        //抛出数据库链接超时异常
        throw new SocketTimeoutException();
    }

    @Operation(summary = "查询当前数据源",description = "查询当前数据源")
    @GetMapping("/getDataSourceNow")
    public Result getDataSourceNow(){
        String peek = DynamicDataSourceContextHolder.peek();
        return Result.ok(peek);
    }

    //@DS("logs")
    @Operation(summary = "添加日志",description = "添加日志")
    @PostMapping("/addLogs")
    public Result addLogs(@RequestBody Users users){
        //切换数据源
        DynamicDataSourceContextHolder.clear();
        DynamicDataSourceContextHolder.push("logs");
        usersService.save(users);
        return Result.ok();
    }




}
